import { defineStore } from "pinia";
import { computed, ref } from "vue";
import type { OrderCreateParams, OrderCreateResult, OrderPreResult, OrderResult } from "@/types/order";
import { fetchNowOrderPreAPI, fetchOrderDetailAPI, fetchOrderPreAPI, payWxPayMiniPayAPI, submitOrderAPI } from "@/api/orderApi";
import type { Address } from "@/types/address";

const useOrderStore = defineStore("orderStore", () => {
    /*订单预支付的信息*/
    const orderPre = ref<OrderPreResult>(<OrderPreResult>{});
    /*订单详情*/
    const orderDetail = ref<OrderResult>(<OrderResult>{});

    /*默认的收货地址*/
    const defaultAddress = computed<Address | undefined>(() => orderPre.value.userAddresses?.find(item => item.isDefault === 1));
    /*获取订单预支付的请求函数*/
    const fetchOrderPre = async (): Promise<void> => {
        const { result }: { result: OrderPreResult } = await fetchOrderPreAPI();
        orderPre.value = result;
    };
    /*立即购买订单的请求函数*/
    const fetchNowOrderPre = async (params: { skuId: string, count: string, addressId?: string }): Promise<void> => {
        const { result }: { result: OrderPreResult } = await fetchNowOrderPreAPI(params);
        orderPre.value = result;
    };

    /*提交订单的请求函数*/
    const submitOrder = async (data: OrderCreateParams): Promise<string> => {
        const { result }: { result: OrderCreateResult } = await submitOrderAPI(data);
        return result.id;
    };

    /*获取订单详情的请求函数*/
    const fetchOrderDetail = async (id: string): Promise<void> => {
        const { result }: { result: OrderResult } = await fetchOrderDetailAPI(id);
        orderDetail.value = result;
    };

    /*获取微信支付参数的请求函数*/
    const payWxPayMiniPay = async (params: { orderId: string }): Promise<any> => {
        const { result } = await payWxPayMiniPayAPI(params);
        return result;
    };

    return {
        orderPre,
        orderDetail,
        defaultAddress,
        fetchOrderPre,
        fetchNowOrderPre,
        submitOrder,
        fetchOrderDetail,
        payWxPayMiniPay,
    };
});


export default useOrderStore;
